package eu.jpereira.trainings.designpatterns.creational.builder;

import java.util.Iterator;

import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBody;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SaleEntry;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SoldItem;
import eu.jpereira.trainings.designpatterns.creational.builder.json.JSONReportBody;

public class JSONBuilder implements BodyBuilder {
	
	private SaleEntry saleEntry;
	private JSONReportBody body;

	@Override
	public void construct(SaleEntry saleEntry) {
		// TODO Auto-generated method stub
		this.saleEntry = saleEntry;
		body = new JSONReportBody();

	}

	@Override
	public void addCustomerInfo() {
		// TODO Auto-generated method stub
		body.addContent("sale:{customer:{");
        body.addContent("name:\"");
        body.addContent(this.saleEntry.getCustomer().getName());
        body.addContent("\",phone:\"");
        body.addContent(this.saleEntry.getCustomer().getPhone());
        body.addContent("\"}");

	}

	@Override
	public void addItems() {
		// TODO Auto-generated method stub
		body.addContent(",items:[");
        Iterator<SoldItem> it = this.saleEntry.getSoldItems().iterator();

        while ( it.hasNext() ) {
            SoldItem item = it.next();
            body.addContent("{name:\"");
            body.addContent(item.getName());
            body.addContent("\",quantity:");
            body.addContent(String.valueOf(item.getQuantity()));
            body.addContent(",price:");
            body.addContent(String.valueOf(item.getUnitPrice()));
            body.addContent("}");
            if ( it.hasNext() ) {
                body.addContent(",");
            }

        }
        body.addContent("]}");

	}

	@Override
	public ReportBody getBody() {
		// TODO Auto-generated method stub
		return this.body;
	}

}
